import os
import json

print(os.getcwd())
print(os.listdir())

with open('./config.json') as f:
    root_path = json.load(f)['root_path'].replace('\\','/')
os.chdir(root_path)
docsify_root_dir = ''


def is_pic_dir(name):
    return name == "pictures"


def is_md(name):
    return name.split(".")[-1] == "md"

def is_ignore_file(name):
    files = [
        '_navbar.md',
        '_sidebar.md'
    ]
    if name in files: return True

def check_file(name, ignore_md = False):
    if ignore_md: return not is_pic_dir(name) and not is_ignore_file(name)
    else: return not is_pic_dir(name) and is_md(name) and not is_ignore_file(name)


def write_sidebar(dir_path='', cp = ''):
    current_path = (cp + dir_path) if cp else root_path.replace("\\", "/") # 当前主机路径
    os.chdir(current_path)
    docsify_current_path = (  # docsify的绝对路径
        docsify_root_dir.join(current_path.split(root_path))
    ).replace("\\", "/")
    all = os.listdir() # 当前主机路径下的所有文件和目录
    dirs = []
    files = []
    lines = []

    for item in all:
        if os.path.isdir(item):
            # 格式化目录行
            if not is_pic_dir(item):
                line = f"\n- {item}"
                lines.append(line)

                # 遍历目录，获得目录里的文件
                second_level_dirs = os.listdir(f"{current_path}/{item}")
                docsify_current_path_tmp = (
                    docsify_root_dir.join(f"{current_path}/{item}".split(root_path))
                ).replace("\\", "/")
                # print(second_level_dirs)
                for file in second_level_dirs:
                    # 如果是非图片文件夹
                    if check_file(file, ignore_md=True):
                        # 如果是文件夹
                        if os.path.isdir(f"{current_path}/{item}/{file}"):
                            files = os.listdir(f"{current_path}/{item}/{file}")
                            for i in files:
                                if check_file(i):
                                    file_name = file.split(".")[0]
                                    line = f"\n  - [{file_name}]({docsify_current_path_tmp}/{file}/{i})"
                                    lines.append(line)
                        # 如果是md文件
                        elif check_file(file):
                            file_name = file.split(".")[0]
                            line = f"\n  - [{file_name}]({docsify_current_path_tmp}/{file})"
                            lines.append(line)
                        # for i in files:
                        #     if check_file(i):
                        #         file_name = i.split(".")[0]
                        #         line = f"\n  - [{file_name}]({docsify_current_path_tmp}/{i})"
                        #         lines.append(line)
                        #         break

                dirs.append(item)
        else:
            files.append(item)

    # 处理完文件夹再处理文件
    # 筛选是否为md文件或非图片文件夹
    for item in files:
        if check_file(item):
            file_name = item.split('.')[0]
            line = f'\n- [{file_name}]({docsify_current_path}/{item})'
            lines.append(line)

    # 写入文件
    with open("_sidebar.md", "w") as f:
        before_dir = '/'.join(docsify_current_path.split('/')[:-1]) if '/'.join(docsify_current_path.split('/')[:-1]) else '/'
        current_dir = docsify_current_path.split('/')[-1]
        if not dir_path:
            result = [f'- 首页',f'\n- {current_dir}']
        else:
            result = [
                f'- [返回首页](/)',
                f'\n- [返回上一级]({before_dir})',
                f'\n- {current_dir}'
            ]
        result.extend(lines)
        f.writelines(result)

    # 递归，进入二级目录继续重复上述操作
    if len(dirs) > 0:
        for i in dirs:
            write_sidebar(f'/{i}', current_path)


def main():
    write_sidebar()


if __name__ == "__main__":
    main()
